package com.wanmait.schedule.util;

import com.aliyun.oss.OSSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("upImage")
public class UpImageController {
    @Value("${spring.cloud.alicloud.oss.maxSize}")
    private int maxSize;
    @Value("${spring.cloud.alicloud.oss.bucketName}")
    private String bucketName;
    @Value("${spring.cloud.alicloud.oss.dir.prefix}")
    private String dirPrefix;
    @Value("${spring.cloud.alicloud.oss.domainName}")
    private String domainName;

    @Resource
    private OSSClient ossClient;

    @RequestMapping("upload")
    public AjaxResult uploadToOSS(@RequestParam("photo") MultipartFile file) {
        String url = "";
        try {
            InputStream inputStream = file.getInputStream();
            String objectName =  getObjectName(file);
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream);
            url = formatPath(objectName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(url);
    }

    private String getObjectName(MultipartFile file) {
        // 文件后缀
        String suffixName = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = dirPrefix+UUID.randomUUID()+ suffixName;
        return fileName;
    }

    private String formatPath(String objectName){
//        return "https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + objectName;
        return "https://" + domainName + "/" + objectName;
    }



}
